package com.gitee.xmhzzz.component.web.utils;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.gitee.xmhzzz.component.common.dto.BaseUserInfo;
import com.gitee.xmhzzz.component.common.enums.ResponseCode;
import com.gitee.xmhzzz.component.common.exception.DefaultBusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
  * @ClassName
  * @Description
  * @Author wzq
  * @Date 2023/12/18 10:19
  * @Version 1.0
  */
public class RequestContextMng {
    private static final Logger log = LoggerFactory.getLogger(RequestContextMng.class);
    private static ThreadLocal<RequestContext> contextThreadLocal = TransmittableThreadLocal.withInitial(RequestContext::new);

    public static void clear() {
        contextThreadLocal.remove();
    }

    public static void context(RequestContext context) {
        contextThreadLocal.set(context);
    }

    public static RequestContext context() {
        return contextThreadLocal.get();
    }

    public static void setLoginInfo(BaseUserInfo user) {
        contextThreadLocal.get().setUserInfo(user);
    }

    public static <T extends BaseUserInfo> T getLoginInfo(Class<T> expectType) {
        BaseUserInfo user = getLoginInfo();
        if (!expectType.isInstance(user)) {
            log.error("获取登录信息失败, 登录类型与期望的登录类型不匹配, 登录类型: {}, 期望的登录类型: {}", user.getClass(), expectType);
            DefaultBusinessException.of(ResponseCode.BAD_REQUEST);
        }
        return (T) user;
    }

    public static <T extends BaseUserInfo> T getLoginInfo() {
        return getLoginInfo(true);
    }

    @SuppressWarnings("unchecked")
    public static <T extends BaseUserInfo> T getLoginInfo(boolean check) {
        BaseUserInfo loginInfo = contextThreadLocal.get().getUserInfo();
        if (check && loginInfo == null) {
            DefaultBusinessException.of(ResponseCode.NO_LOGIN);
        }
        return (T) loginInfo;
    }
}
